package com.h117121.fashionshop.customeditor;

import java.beans.PropertyEditorSupport;
import java.util.ArrayList;
import java.util.List;

import com.h117121.fashionshop.core.dom.BaseDom;

public class BaseDomCustomEditor<T extends BaseDom> extends
		PropertyEditorSupport {
	private List<T> entities = new ArrayList<T>();

	public BaseDomCustomEditor(List<T> entities) {
		super();
		this.entities = entities;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String getAsText() {
		T value = (T) getValue();
		return (value != null ? "" + value.getId() : "");
	}

	@Override
	public void setAsText(String text) {
		try {
			long id = Long.parseLong(text);

			for (T entity : entities) {
				if (entity.getId() == id) {
					setValue(entity);
					return;
				}
			}
		} catch (IllegalArgumentException ex) {
			setValue(null);
		}

		setValue(null);
	}
}
